package com.example.wallpaperapp.ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.app.WallpaperManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;


import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.example.wallpaperapp.R;
import com.example.wallpaperapp.Service.WallService;
import com.example.wallpaperapp.bean.HomeImageRecyclerViewBean;
import com.example.wallpaperapp.ui.fragment.HottestFragment;
import com.example.wallpaperapp.utils.ToastUtil;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.List;

import retrofit2.http.Url;

public class Activity_preview extends AppCompatActivity {

    public RelativeLayout bg;
    public Bitmap img_drawable;
    String sourceId;
    private ImageView share;
    private ImageView left;
    private ImageView right;
    private int activity_num;
    private int i =0;
    int[] img_array_list;
    String[] img_array;
    private ImageView mDown;


    public static void startActivity_preview(Context context, String sourceId){
        Intent intent = new Intent(context,Activity_preview.class);
        intent.putExtra("sourceId",sourceId);
        context.startActivity(intent);
    }
    public static void startActivity_preview_list(Context context, String sourceId, String[] img_list){
        Intent intent_list = new Intent(context,Activity_preview.class);
        intent_list.putExtra("sourceId_list",sourceId);
        intent_list.putExtra("img_list",img_list);
        intent_list.putExtra("activity", 1);
        context.startActivity(intent_list);
    }
    public void startService() {
        startService(new Intent(getBaseContext(), WallService.class));
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_preview);
        WallpaperManager wallpaperManager = WallpaperManager.getInstance(this);
        initDown();
        left=(ImageView)findViewById(R.id.left);
        right=(ImageView)findViewById(R.id.right);
        bg = (RelativeLayout)findViewById(R.id.preview);
        Button ok  =(Button) findViewById(R.id.ok);
        Button ok_1  =(Button) findViewById(R.id.ok_1);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        Intent intent=getIntent();
        left.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                bg.setBackground(new BitmapDrawable(img_drawable));
                SimpleTarget<Drawable> simpleTarget = new SimpleTarget<Drawable>() {
                    @Override
                    public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
                        bg.setBackground(resource);
                    }
                };
//                bg.setBackgroundResource(sourceId);
                Glide.with(Activity_preview.this).load(img_array[i]).into(simpleTarget);

                if(i==0){
                    i=5;
//                    bg.setBackgroundResource(img_array[i]);
//                    Toast.makeText(getApplication(),"已经是第一张壁纸了",Toast.LENGTH_SHORT).show();
                }
                if(i<img_array.length&&i>0){
                    i--;}
//                bg.setBackgroundResource(img_array[i]);
                Glide.with(Activity_preview.this).load(img_array[i]).into(simpleTarget);


            }
        });
        right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(i<img_array.length){
                    i++;
                }
                if(i==img_array.length){
                    i=0;
//                    Toast.makeText(getApplication(),"已经是最后一张壁纸了",Toast.LENGTH_SHORT).show();

                }
                bg.setBackground(new BitmapDrawable(img_drawable));
                SimpleTarget<Drawable> simpleTarget = new SimpleTarget<Drawable>() {
                    @Override
                    public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
                        bg.setBackground(resource);
                    }
                };
//                bg.setBackgroundResource(img_array_list[i]);
                Glide.with(Activity_preview.this).load(img_array[i]).into(simpleTarget);

            }

        });
        Bundle bundle = this.getIntent().getExtras();
        img_array = bundle.getStringArray("img_list");


        ok_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                    for (int i = 0; i < 7; i++) {
//                        try {
//                            wallpaperManager.setResource(img_array[i]);
//                        } catch (IOException e) {
//                            e.printStackTrace();
//                        }
//                    }
                Intent intent_img_list = new Intent(Activity_preview.this,WallService.class);
                intent_img_list.putExtra("intent_img_list",img_array);
                startService(intent_img_list);

                Intent intent_start = new Intent(Activity_preview.this, WallService.class);
                intent_start.putExtra("start", 0);
                startService(intent_start);
                Toast.makeText(getApplicationContext(),"您已成功设置动态壁纸",Toast.LENGTH_SHORT).show();
                startService(intent_img_list);
//                    Intent intent_2 = new Intent(Activity_preview.this, WallService.class);
//                    startActivity(intent_2);
                PendingIntent pi = PendingIntent.getService(getApplicationContext(),0, new Intent("SERVICE_TO_SETWALL"), PendingIntent.FLAG_UPDATE_CURRENT);

                AlarmManager alarmManager = (AlarmManager) getSystemService(Service.ALARM_SERVICE);
                // 类型 ，执行延迟的时间，实行时间间隔，动作
                alarmManager.setRepeating(alarmManager.RTC_WAKEUP, 0, 1000, pi);
            }
        });


            if(intent.getStringExtra("sourceId")!=null) {
                sourceId = getIntent().getStringExtra("sourceId");
                img_drawable = returnBitMap(sourceId);
//                bg.setBackgroundResource(sourceId);
                bg.setBackground(new BitmapDrawable(img_drawable));
                SimpleTarget<Drawable> simpleTarget = new SimpleTarget<Drawable>() {
                    @Override
                    public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
                        bg.setBackground(resource);
                    }
                };
                Glide.with(this).load(sourceId).into(simpleTarget);
            }else {
                sourceId = getIntent().getStringExtra("sourceId");
                img_drawable = returnBitMap(sourceId);
                bg.setBackground(new BitmapDrawable(img_drawable));
                SimpleTarget<Drawable> simpleTarget = new SimpleTarget<Drawable>() {
                    @Override
                    public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
                        bg.setBackground(resource);
                    }
                };
                Glide.with(this).load(img_array[i]).into(simpleTarget);
            }


        ImageView imageView  =(ImageView) findViewById(R.id.preview_return);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        share=(ImageView) findViewById(R.id.preview_share);
        share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                allShare();
            }
        });
        ImageView like  =(ImageView) findViewById(R.id.preview_like);
        like.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                like.setImageResource(R.drawable.collect_clicked);
                Toast.makeText(getApplicationContext(),"您已收藏该壁纸",Toast.LENGTH_SHORT).show();
            }
        });

        Uri imageUri = getUriFromDrawableRes(getApplicationContext(),R.drawable.img_1);


        InputStream inputStream = null;
        try {
            inputStream = getContentResolver().openInputStream(imageUri);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }


        InputStream finalInputStream = inputStream;

        ok.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("ResourceType")
            @Override
            public void onClick(View v) {

                try {
                    img_drawable = returnBitMap(sourceId);
//                    wallpaperManager.setResource(sourceId);
                    wallpaperManager.setBitmap(img_drawable);
                    Toast.makeText(getApplicationContext(), "您已成功设置手机壁纸", Toast.LENGTH_SHORT).show();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                    Intent intent_stop = new Intent(Activity_preview.this, WallService.class);
                    intent_stop.putExtra("stop", 4);
                    startService(intent_stop);


            }
        });

        Intent intent_1 = getIntent();
        activity_num=intent_1.getIntExtra("activity",0);
        if(activity_num==1){
            ok.setVisibility(View.GONE);
        }
        if(activity_num==0){
            left.setVisibility(View.GONE);
            right.setVisibility(View.GONE);
            ok_1.setVisibility(View.GONE);
        }
    }

    /**
     * 得到资源文件中图片的Uri
     * @param context 上下文对象
     * @param id 资源id
     * @return Uri
     */
    public Uri getUriFromDrawableRes(Context context, int id) {
        Resources resources = context.getResources();
        String path = ContentResolver.SCHEME_ANDROID_RESOURCE + "://"
                + resources.getResourcePackageName(id) + "/"
                + resources.getResourceTypeName(id) + "/"
                + resources.getResourceEntryName(id);
        return Uri.parse(path);
    }

    /**
     * Android原生分享功能
     * 默认选取手机所有可以分享的APP
     */
    public void allShare(){
        Intent share_intent = new Intent();
        share_intent.setAction(Intent.ACTION_SEND);//设置分享行为
        share_intent.setType("text/plain");//设置分享内容的类型
        share_intent.putExtra(Intent.EXTRA_SUBJECT, "好好看的壁纸呀");//添加分享内容标题
        share_intent.putExtra(Intent.EXTRA_TEXT, "分享给你一张好看的壁纸！");//添加分享内容
        //创建分享的Dialog
        share_intent = Intent.createChooser(share_intent, "share");
        startActivity(share_intent);
    }

    //--------------------------------------------------------------
    private void initDown() {


        //第二个参数是需要申请的权限
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED)
        {
            //没有授权进行权限申请
            ActivityCompat.requestPermissions(Activity_preview.this, new String[]{ Manifest.permission. WRITE_EXTERNAL_STORAGE }, 1);
        }
        mDown=findViewById(R.id.download_img);
        imgURl = sourceId;
        mDown.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                new Thread(downloadRunn).start();
                mDown.setClickable(false);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        mHandler.obtainMessage(SAVE_BEGIN).sendToTarget();
                        Bitmap bp=returnBitMap(imgURl);
                        saveImageToPhotos(getBaseContext(),bp);
                    }
                }).start();
            }
        });
    }
    private void saveImageToPhotos(Context context, Bitmap bmp) {
        // 首先保存图片
        File appDir = new File(Environment.getExternalStorageDirectory(), "Boohee");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 其次把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(),
                    file.getAbsolutePath(),fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            mHandler.obtainMessage(SAVE_FAILURE).sendToTarget();
            return;
        }
        // 最后通知图库更新
//        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file)));

//        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
//        Uri uri = Uri.fromFile(file);
//        intent.setData(uri);
//        context.sendBroadcast(intent);
        mHandler.obtainMessage(SAVE_SUCCESS).sendToTarget();
    }
    /**
     * 将URL转化成bitmap形式
     *
     * @param url
     * @return bitmap type
     */
    public Bitmap returnBitMap(final String url){

        new Thread(new Runnable() {
            @Override
            public void run() {
                URL imageurl = null;
                try {
                    imageurl = new URL(sourceId);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }

                try {
                    imageurl = new URL(url);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
                try {
                    if (imageurl!=null){
                        HttpURLConnection conn = (HttpURLConnection)imageurl.openConnection();
                        conn.setDoInput(true);
                        conn.connect();
                        InputStream is = conn.getInputStream();
                        bitmap = BitmapFactory.decodeStream(is);
                        is.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        return bitmap;
    }
    private String imgURl;//图片的URL地址
    private static final int SAVE_SUCCESS = 0;//保存图片成功
    private static final int SAVE_FAILURE = 1;//保存图片失败
    private static final int SAVE_BEGIN = 2;//开始保存图片
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SAVE_BEGIN:
                    ToastUtil.makeText(Activity_preview.this,"开始保存图片...");
                    mDown.setClickable(false);
                    break;
                case SAVE_SUCCESS:
                    ToastUtil.makeText(Activity_preview.this,"图片保存成功,请到相册查找");
                    mDown.setClickable(true);
                    break;
                case SAVE_FAILURE:
                    ToastUtil.makeText(Activity_preview.this,"图片保存失败,请稍后再试...");
                    mDown.setClickable(true);
                    break;
            }
        }
    };

    //把URL转为Bitmap数组
    public static Bitmap[] getBitmapFromURL(String[] path) throws MalformedURLException {

        Bitmap[] b = new Bitmap[path.length];

        for (int i = 0; i < path.length; i++) {
            URL url = new URL(path[i]);
            HttpURLConnection conn = null;
            try {
                conn = (HttpURLConnection)url.openConnection();
                conn.setConnectTimeout(5000);
                conn.setRequestMethod("GET");
                if(conn.getResponseCode() == 200){
                    InputStream inputStream = conn.getInputStream();
                    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                    b[i]=bitmap;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return b;
    }

    private Bitmap bitmap;


}